import ls from '@/utils/Storage'
import { MENU_NAV, PERMISSION, ROLE } from '@/store/mutation-types'
import { buildMenuTree, buildRouterTree } from '@/utils/menu'
/**
 * 格式:{app:[]}
 * @param router
 * @param menu
 */
const generateAsyncRoutes = (router, menu?) => {
  let menuNav = {}
  // 后端数据, 根级树数组,  根级 PID
  const menuData = ls.get(MENU_NAV)
  if (!menuData && !menu) return
  // 若有缓存,则从缓存取菜单内容,然后直接生成路由
  if (!menu && menuData) {
    menuNav = menuData
  } else {
    if (menuData) {
      Object.keys(menuData).forEach((key) => {
        if (key != Object.keys(menu)[0]) {
          menuNav[key] = menuData[key]
        }
      })
    }
    Object.keys(menu).forEach((key) => {
      const item = buildMenuTree(key, menu[key], ls.get(ROLE), ls.get(PERMISSION))
      menuNav[key] = item
    })
    ls.set(MENU_NAV, menuNav)
  }
  Object.keys(menuNav).forEach((key) => {
    const routers = buildRouterTree(menuNav[key], key)
    routers.forEach((item) => {
      router.addRoute(item)
    })
  })
}

export default generateAsyncRoutes
